import streamlit as st
import datetime
import requests
import json
from chinese_calendar import get_lunar_date

st.set_page_config(page_title="一键性格报告", page_icon="🔮")
st.title("🔮 一键性格报告")

with st.form("info"):
    dt_str = st.text_input("阳历生日+时间（格式 2000-01-01 18:30）", "2000-01-01 18:30")
    blood = st.selectbox("血型", ["A", "B", "AB", "O"])
    mbti  = st.selectbox("MBTI", ["ISTJ","ISFJ","INFJ","INTJ","ISTP","ISFP","INFP","INTP",
                                  "ESTP","ESFP","ENFP","ENTP","ESTJ","ESFJ","ENFJ","ENTJ"])
    sign  = st.selectbox("星座", ["白羊座","金牛座","双子座","巨蟹座","狮子座","处女座",
                                  "天秤座","天蝎座","射手座","摩羯座","水瓶座","双鱼座"])
    submitted = st.form_submit_button("生成报告")

if submitted:
    try:
        dt = datetime.datetime.strptime(dt_str, "%Y-%m-%d %H:%M")
        lunar = get_lunar_date(dt.year, dt.month, dt.day)
        bazi = f"{lunar.year}{lunar.month}{lunar.day}{lunar.hour}"  # 简易版
    except:
        st.error("日期格式错误！请用 yyyy-mm-dd hh:mm")
        st.stop()

    prompt = f"""
你是一名中文性格分析师。请结合以下信息，用 150 字左右、口语化、温暖的方式描述性格特点与建议：
八字：{bazi}
血型：{blood}
MBTI：{mbti}
星座：{sign}
"""
    headers = {"Authorization": f"Bearer {st.secrets['GLM_KEY']}",
               "Content-Type": "application/json"}
    payload = {
        "model": "glm-4-flash",
        "messages": [{"role": "user", "content": prompt}]
    }
    resp = requests.post("https://open.bigmodel.cn/api/paas/v4/chat/completions",
                         headers=headers, json=payload, timeout=30)
    if resp.status_code == 200:
        result = resp.json()["choices"][0]["message"]["content"]
        st.success(result)
    else:
        st.error("调用 AI 失败，请检查网络或 API Key")